<?php
/**
 * 文件描述  Mysql操作类
 * =================================================================
 * 文件名称  Mysql.class.php
 * -----------------------------------------------------------------
 * 作    者  xiaokai<601200376@qq.com>
 * -----------------------------------------------------------------
 * 创建时间  2010-1-19
 * -----------------------------------------------------------------
 * 版权信息  创思工作室
 * =================================================================
 */

class Mysql extends DataBase
{
    /**
     * 连接数据库
     * @access  public
     * @return  reource
     */
    public function connect($host, $user, $password, $name, $pconnect, $table, $return)
    {
        $func = $pconnect ? 'mysql_pconnect' : 'mysql_connect';
        $this->_conn = $func($host, $user, $password);
        $this->selectDataBase($name);
        $this->query('SET NAMES utf8');
        $this->_fetchFunc = $return == 'array' ? 'mysql_fetch_array' : ($return == 'object' ? 'mysql_fetch_object' : 'mysql_fetch_assoc');
        $this->_table     = $table;
        return $this->_conn;
    }

    /**
     * 选择数据库
     *
     * @access	access
     * @param   string  $database   数据库名称
     * @return	bool
     */
    public function selectDataBase($dataBase)
    {
        return mysql_select_db($dataBase);
    }

    /**
     * 执行SQL命令
     *
     * @access	public
     * @param   string  $sql
     * @return	object
     */
    public function query()
    {
        $this->formatSqlStr(func_get_args());
        $this->_result = @mysql_query($this->_sqlStr, $this->_conn) or $this->halt('', true);
        $this->_queryCount++;
        return $this;
    }

    /**
     * 执行SQL命令返回影响记录数
     * @access  public
     * @param   string  $sql
     * @return  int
     */
    public function execute()
    {
        $this->formatSqlStr(func_get_args());
        @mysql_query($this->_sqlStr, $this->_conn) or $this->halt('', true);
        $this->_queryCount++;
        return $this->affectedRows();
    }

    /**
     * 插入记录
     * @access	public
     * @param	array   $data   记录
     * @return	int             记录ID
     */
    public function insert($data)
    {
        $fields = $values = array();
        foreach ($data as $key => $val) {
            $fields[] = "`{$key}`";
            $values[] = is_numeric($val) ? (int)$val : mysql_real_escape_string($val);
        }
        $fields = join(',', $fields);
        $values = join(',', $values);
        $sql = "INSERT INTO {$this->_table} ({$fields}) VALUES ({$values})";
        return $sql;
    }

    /**
     * 更新记录
     * @access	public
     * @param	array   $data   记录
     * @return	int             影响记录行数
     */
    public function update($data, $where)
    {
        $values = array();
        foreach ($data as $key => $val)
        {
            $values[] = "`{$key}`='" . mysql_real_escape_string($val) . "'";
        }
        $sql = "UPDATE {$this->_table} SET " . join(',', $values);
        return $sql;
    }

    /**
     * 删除记录
     * @access	public
     * @param	string  $where  删除条件
     * @return	int             影响行数
     */
    public function delete($where)
    {
        $sql = "DELETE {$this->_table} WHERE {$where}";
        return $sql;
    }

    /**
     * 查询符合条件的所有记录
     * @access	public
     * @param	array   $args   查询参赛
     * @param	bool    $all    是否返回所有， 默认为true
     * @return	mixed
     */
    public function findAll($args, $all = true)
    {
        $sql   = 'SELECT ';
        $table = isset($args['table']) ? $args['table'] : '__TABLE__';
        $join  = @join(' LEFT JOIN ', @$args['join']);
        $sql  .= isset($args['count']) ? "COUNT({$args['count']}) AS count" : ' ';
        $sql  .= isset($args['field']) && !isset($args['count']) ? $args['field'] : ' ';
        $sql  .= " FROM {$table} ";
        $sql  .= isset($args['join'])   ? ' LEFT JOIN ' . $join : ' ';
        $sql  .= isset($args['where'])  ? ' WHERE '     . $args['where']  : ' ';
        $sql  .= isset($args['group'])  ? ' GROUP '     . $args['group']  : ' ';
        $sql  .= isset($args['having']) ? ' HAVING '    . $args['having'] : ' ';
        $sql  .= isset($args['order'])  ? ' ORDER BY '  . $args['order']  : ' ';
        $sql  .= isset($args['limit'])  ? ' LIMIT '     . $args['limit']  : ' ';
        $this->query($sql);
        return $all ? $this->fetchAll() : $this->fetchOne();
    }

    /**
     * 获取一条结果集
     * @access  public
     * @return  mixed
     */
    public function fetchOne()
    {
        $func = $this->_fetchFunc;
        return $func($this->_result);
    }

    /**
     * 获取所有结果集
     * @access  public
     * @return  array
     */
    public function fetchAll()
    {
        $rows = array();
        while ($row = $this->fetchOne()) {
            $rows[] = $row;
        }
        return $rows;
    }

    /**
     * 操作影响行数
     * @access  public
     * @return  bool
     */
    public function affectedRows()
    {
        return mysql_affected_rows($this->_conn);
    }

    /**
     * 插入记录id
     * @access  public
     * @return  bool
     */
    public function insertId()
    {
        return mysql_insert_id();
    }

    /**
     * 清空结果集
     * @access  public
     * @return  bool
     */
    public function free()
    {
        if (is_resource($this->_result)) {
            return mysql_free_result($this->_result);
        }

    }

    /**
     * 关闭数据库
     * @access  public
     * @return  bool
     */
    public function close()
    {
        if (is_resource($this->_conn)) {
            return mysql_close($this->_conn);
        }
    }

    /**
     * 返回错误信息
     * @access  public
     * @return  string
     */
    public function error()
    {
        $this->_errStr = mysql_error($this->_conn);
        return $this->_errStr;
    }
}